package com.wang.common.filter;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @description 请求流转换成多次读取的请求流 过滤器
 * @since 2022-12-12
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1) //优先级最高
public class HttpServletRequestInputStreamFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 转换为可以多次获取流的request
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        InputStreamHttpServletRequestWrapper inputStreamHttpServletRequestWrapper = new InputStreamHttpServletRequestWrapper(request);
        // 放行
        filterChain.doFilter(inputStreamHttpServletRequestWrapper, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
